import { defineStore } from 'pinia';
import { dingZhiActivity } from '@/enums/activityEnum';
import { splitArrayIntoChunks, joinURL } from '@/utils/publicMethods';
import { langObjMap } from '@/enums/langEnum';
import { GameType } from "@/enums/gameEnum.ts";

/**
 * 页面信息
 * @methods setUserInfos 设置用户信息
 */
interface PageState {
    menuActive: number
    countryOptions: any
    bannerArr: any
    textAnnouncement: any
    serviceUrlObj: any
    settings: any,
    pageLoading: boolean,
    gameIsLoading: boolean,
    hotGameIsLoading: boolean,
    adminI18n: any
    lang: string,
    langLoading: boolean,
    unread: number,
    homeGameData: any,
    activityList: any,
    activityTitleList: any,
    showLeft: boolean,
    showRight: boolean,
    hotBoxGames: any,
    defaultActivityList: any,
    isBackFromGame: boolean,
}

let loadingCount = 0 // 加载计数
export const Page = defineStore('pages', {

    state: (): PageState => ({
        menuActive: -1,
        countryOptions: null,
        bannerArr: [],
        textAnnouncement: [],
        serviceUrlObj: {},
        settings: null,
        homeGameData: [],
        pageLoading: false,
        gameIsLoading: false,
        hotGameIsLoading: false,
        adminI18n: null,
        lang: '',
        langLoading: false,
        unread: 0,
        defaultActivityList: null,
        activityList: sessionStorage.getItem('activityList') ? JSON.parse(sessionStorage.getItem('activityList') || '[]') : null,
        activityTitleList: null,
        showLeft: false,
        showRight: false,
        hotBoxGames: [], // HomeGameHotBox 的游戏数据
        isBackFromGame: false // 是否是从3方游戏里返回的
    }),
    actions: {
        setShowLeft(val: boolean) {
            if (val) {
                location.href = location.href.replace('#menu', '') + `#menu`
            }
            setTimeout(() => {
                this.showLeft = val
            })
        },
        setShowRight(val: boolean) {
            this.showRight = val
        },
        // 获取未读消息数量
        async getUnread(isFirst = false) {
            if (isFirst) {
                this.unread = 0
            }
            const chat_info: any = this.$state.settings?.chat_res?.chat_info
            let device_id
            if (localStorage.getItem('deviceid')) {
                device_id = localStorage.getItem('deviceid') || ''
            }
            //  device_id = localStorage.getItem('deviceid')
            if (chat_info && device_id) {
                let url = joinURL(chat_info, `/api/message/unread?device_id=${device_id}`)
                fetch(url)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok ' + response.statusText);
                        }
                        return response.json(); // 将响应解析为 JSON
                    })
                    .then(res => {
                        console.log('消息', res?.data)
                        this.unread = res?.data?.count || 0
                    })
            }
        },

        async setHomePageGameData(data: any) {
            data.map((e: any) => {
                if (e.id == 0) { // 热门一组8个
                    e.newList = splitArrayIntoChunks(e.three_platform, 8)
                } else { // 其他一组6个
                    const hosList: any = []
                    e.three_platform.forEach((plat: any) => {
                        if ([GameType.Live, GameType.Sports].includes(plat.venue_id)) {
                            if (plat.is_hot == 1) {
                                hosList.push(plat)
                            }
                        } else {
                            if (plat.three_game_kind) {
                                plat.three_game_kind.forEach((room: any) => {
                                    if (room.three_game) {
                                        room.three_game.forEach((game: any) => {
                                            if (game.is_hot == 1) {
                                                hosList.push(game)
                                            }
                                        })
                                    }
                                })
                            }
                        }
                    })
                    e.newList = splitArrayIntoChunks(hosList, 6)
                }
            })
            data.map((e: any) => {
                let target: any = this.homeGameData.find((b: any) => b.id == e.id)
                if (!target) {
                    this.homeGameData.push(e)
                } else {
                    target = e
                }
            })
            this.homeGameData = JSON.parse(JSON.stringify(this.homeGameData))
        },
        async setSettings(value: any) {
            this.settings = value
        },
        async setAdminI18n(value: any) {
            this.adminI18n = value
        },
        async setPageLoading(value: any) {
            this.pageLoading = value
        },
        async setHotGameIsLoading(value: any) {
            this.hotGameIsLoading = value
        },
        async setGameIsLoading(value: any) {
            if (value) {
                loadingCount++
            } else {
                loadingCount--
                if (loadingCount < 0) loadingCount = 0
            }
            this.gameIsLoading = loadingCount ? true : false
        },
        setBackFromGame(value: any) {
            this.isBackFromGame = value
        },
        async setLangLoading(value: any) {
            this.langLoading = value
        },
        async setLang(value: any) {
            this.lang = value


            if (!this.adminI18n) return
            this.serviceUrlObj = null
            this.bannerArr = null
            let strs = value.split('-')
            let str = strs[0]
            if (strs[0] == 'vi') {
                str = 'vn'
            }
            let keys = Object.keys(this.adminI18n[str])
            let bannerArr: Array<string> = []
            let serviceUrlObj: any = {}
            keys.map((e: string) => {
                if (e.indexOf('pc') == -1 && e.indexOf('admin_banner_list') != -1) {
                    bannerArr.push(e)
                }
                if (e.indexOf('service_') != -1) {
                    serviceUrlObj[e] = this.adminI18n[str][e]
                }
            })
            this.serviceUrlObj = serviceUrlObj
            this.bannerArr = bannerArr

            this.setActivityTitleList(this.defaultActivityList)
        },
        async resetAnnouncement() {
            this.textAnnouncement = []
        },
        async setTextAnnouncementMore(str: string) {
            this.textAnnouncement.push(str)
            this.textAnnouncement.splice(0, 0)
        },
        async setActivityTitleList(value: any) {
            if (!value) return

            this.defaultActivityList = value
            const lang = langObjMap[this.lang] || this.lang

            let newList = value
            newList = newList.map((item: any) => {
                const pic_key = item.pic_link
                const adminLang = this.adminI18n[lang]
                const content_key = pic_key.replace("title", "content")
                let pic_link = adminLang[pic_key]
                if (dingZhiActivity[item.id]) {
                    pic_link = `/imgs/lang/${lang}/activity/${dingZhiActivity[item.id].id}.png`
                }
                return {
                    name: dingZhiActivity[item.id]?.name || adminLang[item.name],
                    pic_link,
                    details: adminLang[item.details] || '',
                    content: adminLang[item.content] || '',
                    restrict: adminLang[item.restrict] || '',
                    pic_content: adminLang[content_key],
                    content_key,
                    rules: adminLang[item.rules] || '',
                    total: item.total || '',
                    id: item.id,
                    tag: dingZhiActivity[item.id]?.tag || item.tag,
                }
            })

            if (newList.length > 0) {
                let obj: any = {
                    home_page_all: newList,
                };
                newList = newList.filter((item: { pic_link: any; }) => item.pic_link && item.pic_link !== null)
                newList.map((e: any) => {
                    obj[e.tag] = [];
                    newList.map((j: any) => {
                        if (j.tag == e.tag) {
                            obj[e.tag].push(j);
                        }
                    });
                });
                this.activityTitleList = obj;
                this.activityList = splitArrayIntoChunks(newList, 4)

                sessionStorage.setItem('activityList', JSON.stringify(this.activityList))
            }
        },
        async updateHotBoxGames(data: any[]) {
            this.hotBoxGames = data;
        },

    }
});
